import { CustomerChannelVO, getCustomerChannelList } from '@/services/CustomerChannelService'
import { convertEnum, covertTableData } from '@/utils/tableUtil'
import {
  ActionType,
  ModalForm,
  PageContainer,
  ProColumnType,
  ProFormDateTimePicker,
  ProFormMoney,
  ProFormSelect,
  ProFormText,
  ProTable,
} from '@ant-design/pro-components'
import { request } from '@umijs/max'
import { Button, message, Space } from 'antd'
import dayjs from 'dayjs'
import { ReactNode, useEffect, useRef, useState } from 'react'

/* ******************* 类型定义 ******************* */

/**
 * 客资渠道投放记录表实体类
 */
export interface DeliverLogVO {
  /**
   * 渠道id
   */
  channelId: string
  /**
   * 投放时间
   */
  deliverTime: string
  /**
   * 本次花费
   */
  fee: number
  /**
   * 编号
   */
  id?: string

  test: string
}

/* ******************* 调用后端接口 ******************* */

const getDeliverLogPage = async (params?: any) => {
  // 请求接口
  let resp = await request<DeliverLogVO>(`/api/v2/deliverLog/deliverLogPage`, { params: params })
  console.log('************', resp)

  return covertTableData(resp)
}

const addDeliverLog = async (dto: DeliverLogVO) => {
  return request<DeliverLogVO>(`/api/v2/deliverLog/addDeliverLog`, { method: 'POST', data: dto })
}

const editDeliverLog = async (dto: DeliverLogVO) => {
  return request<DeliverLogVO>(`/api/v2/deliverLog/editDeliverLog`, { method: 'POST', data: dto })
}

const removeDeliverLog = async (idList: string[]) => {
  return request<DeliverLogVO>(`/api/v2/deliverLog/removeDeliverLog?idList=${idList}`, {
    method: 'POST',
  })
}

// const editDeliverLog =async (dto:DeliverLogVo) => {
//   return request<DeliverLogVO>(`/api/v2/deliverLog/editDeliverLog`,{method:'POST',data:dto})
// }

/* ******************* 页面Element ******************* */
const DeliverLog = () => {
  const [channelList, setChannelList] = useState<CustomerChannelVO[]>([])
  const [currentDeliverLog, setCurrentDeliverLog] = useState<DeliverLogVO>()
  const [isAdd, setIsAdd] = useState(false)
  const [modalOpenState, setModalOpenState] = useState(false)
  const tableRef = useRef<ActionType>()

  useEffect(() => {
    getCustomerChannelList().then((res) => {
      setChannelList(res)
      console.log(res, '*************')
    })
  }, [])

  const columns: ProColumnType<DeliverLogVO>[] = [
    {
      title: '渠道',
      dataIndex: 'channelId',
      valueEnum: convertEnum(channelList, { label: 'channelName', value: 'id' }),
    },
    {
      title: '花费',
      hideInSearch: true,
      dataIndex: 'fee',
      renderText: (text) => `￥${text / 100}`,
    },
    {
      title: '投放时间',
      hideInSearch: true,
      dataIndex: 'deliverTime',
    },

    {
      title: '操作',
      render: (dom, record) => (
        <Space key="edit">
          <Button
            type="link"
            onClick={() => {
              let dto: DeliverLogVO = JSON.parse(JSON.stringify(record))
              dto.fee = dto.fee / 100
              setCurrentDeliverLog(dto)
              setModalOpenState(true)
            }}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            onClick={() => {
              if (record.id !== undefined) {
                removeDeliverLog([record.id])
                  .then(() => {
                    message.success('删除成功').then()
                    tableRef.current?.reload()
                  })
                  .catch((e) => {
                    message.error('删除失败:' + e).then()
                  })
              }
            }}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ]

  const action: ReactNode[] = [
    <Button
      key="add"
      type="primary"
      onClick={() => {
        setIsAdd(true)
        let defaultChannelId: string = ''
        if (channelList.length > 0) {
          defaultChannelId = channelList[0].id
        }

        let initState: DeliverLogVO = {
          channelId: defaultChannelId,
          deliverTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
          fee: 0,
          test: '测试11',
        }
        setCurrentDeliverLog(initState)

        setModalOpenState(true)
      }}
    >
      添加
    </Button>,
  ]

  const handleSubmit = async (formData: DeliverLogVO) => {
    let dto: DeliverLogVO = JSON.parse(JSON.stringify(formData))
    dto.fee = dto.fee * 100
    try {
      if (isAdd) {
        await addDeliverLog(dto)
      } else {
        await editDeliverLog(dto)
      }
    } catch (e) {
      message.error(`操作失败:${e}`)
      return false
    }
    tableRef.current?.reload()
    message.success('操作成功')
    return true
  }

  return (
    <PageContainer>
      <ProTable<DeliverLogVO>
        actionRef={tableRef}
        request={getDeliverLogPage}
        columns={columns}
        toolbar={{ actions: action }}
      />

      <ModalForm<DeliverLogVO>
        key={currentDeliverLog?.id || 0}
        title={isAdd ? '添加记录' : '修改记录'}
        open={modalOpenState}
        onOpenChange={(state) => {
          setModalOpenState(state)
        }}
        initialValues={currentDeliverLog}
        modalProps={{
          destroyOnClose: true,
        }}
        onFinish={handleSubmit}
      >
        <ProFormText label="编号" name="id" disabled hidden />
        <ProFormText label="测试数据" name="test" />
        <ProFormSelect
          label="渠道"
          name="channelId"
          valueEnum={convertEnum(channelList, { label: 'channelName', value: 'id' })}
        />
        <ProFormMoney
          label="投放金额"
          name="fee"
          rules={[
            { required: true, message: '投放金额不能为空' },
            { max: 50000, min: 1, message: '投放金额必须在1~50000之间', type: 'integer' },
          ]}
        />
        <ProFormDateTimePicker label="投放时间" name="deliverTime" />
      </ModalForm>
    </PageContainer>
  )
}

export default DeliverLog
